package com.asiainfo.kbisheet.util

import java.io.File;
import java.sql.Timestamp;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.asiainfo.kbisheet.vo.KbsSheetVO;


class XMLFileUtil {
	protected static final Log log = LogFactory.getLog(XMLFileUtil.class)	
	def sql = (new DBUFactory()).createKbsBaseDBU().getSQLInstance()
	private String root = Setting.getSettingVO().getFilesRoot()
	public void scanXMLDir(){
		log.info "root:" + root
		new File(root).eachFileRecurse { file ->
			if(file.isFile() && !file.isHidden() && file.toString().endsWith(".xml"))
				save(file)
		}	
	}
	
	private void save(File file){
		try{
			def xmlin = new XmlSlurper().parse(file)
			String sourceKey = xmlin.sourceKey
			String databaseName = xmlin.databaseName
			String tableName = xmlin.tableName
			String sheetTitle = xmlin.sheetTitle			
			String xmlName = file.getPath().replaceAll('\\\\', "/") - root
			log.info "发现xmlName:" + xmlName
			if(databaseName.length() > 0 && tableName.length() > 0 && sheetTitle.length() > 0){            
				Timestamp xmlTime = new Timestamp(file.lastModified())
				KbsSheetVO kbsSheetVO = loadKbsSheetVO4Name(xmlName)
				if(kbsSheetVO==null){
					kbsSheetVO = new KbsSheetVO(sheetId:UUID.randomUUID().toString(),sourceKey:sourceKey,databaseName:databaseName,tableName:tableName,sheetTitle:sheetTitle,xmlName:xmlName,xmlTime:xmlTime)
					saveKbsSheetVO(kbsSheetVO)
				}
			}
			else{
				log.error "${xmlName}XML解析出错。"
			}
		}catch(Throwable t){
			
		}
	}
	
	public KbsSheetVO loadKbsSheetVO4Name(String xmlName){
		KbsSheetVO kbsSheetVO
		def row = sql.firstRow("select * from kbs_sheet where XML_NAME = ?",[xmlName])
		if(row!=null)
			kbsSheetVO = mapRow(row)
		kbsSheetVO
	}
	/**
	 * 保存XML文件
	 * @param xmlName
	 * @param content
	 * @return
	 */
	public boolean saveXmlContent(String xmlName,String content){
		def fw= new FileWriter(root+xmlName)
		fw.write(content)
		fw.close()
		true
	}
	
	
	
	private void saveKbsSheetVO(KbsSheetVO kbsSheetVO){
		sql.execute("insert into kbs_sheet(SHEET_ID,SOURCE_KEY,DATABASE_NAME,TABLE_NAME,SHEET_TITLE,XML_NAME,XML_TIME) values(${kbsSheetVO.sheetId},${kbsSheetVO.sourceKey},${kbsSheetVO.databaseName},${kbsSheetVO.tableName},${kbsSheetVO.sheetTitle},${kbsSheetVO.xmlName},${kbsSheetVO.xmlTime})")
	}	
}
